from collections import OrderedDict

from rest_framework import mixins
from rest_framework.generics import ListCreateAPIView, ListAPIView
from rest_framework.mixins import DestroyModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

from goods_app.models import SKU
from user_app.serializers.sku import SkuSerializer


class SKUView(ListCreateAPIView, mixins.UpdateModelMixin,
              mixins.RetrieveModelMixin, mixins.DestroyModelMixin):
    """
    SKU视图
    """

    class MyPagination(PageNumberPagination):
        """自定义分页器"""
        page_query_param = 'page'
        page_size_query_param = 'page_size'

        def get_paginated_response(self, data):
            return Response(OrderedDict([
                ('counts', self.page.paginator.count),  # 获取查询结果总数
                ('lists', data),  # 结果列表
                ('page', self.page.number),  # 当前页码
                ('pages', self.page.paginator.num_pages),  # 总的页码
                ('pagesize',  # 页容量
                 int(self.request.query_params.get(
                     self.page_size_query_param))),

            ]))

    serializer_class = SkuSerializer
    queryset = SKU.objects.all()
    pagination_class = MyPagination

    def get_queryset(self):
        """keyword=<名称|副标题>"""
        keyword = self.request.query_params.get('keyword') or ""
        result = SKU.objects.filter(name__contains=keyword) or \
                 SKU.objects.filter(caption__contains=keyword)
        return result

    def get(self, request, *args, **kwargs):
        if self.kwargs.get(self.lookup_field):
            return self.retrieve(request, *args, **kwargs)
        return self.list(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)
